package com.example.androidmqtt.Controller;

import com.example.androidmqtt.Entry.News;
import com.example.androidmqtt.Service.ServiceImpl.PlateService;
import com.example.androidmqtt.Vo.NewsDetail;
import com.example.androidmqtt.Vo.ResultData;
import com.example.androidmqtt.Vo.SubPlate;
import lombok.extern.log4j.Log4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author: pjg
 * @time: 2022/9/13
 */
@EnableAsync
@CrossOrigin
@RestController
public class PlateController {

    @Resource
    private PlateService plateService;

    //news 文件保存路径
    private static final String FILE_PATH = "D:\\File\\Android\\AndroidMqtt\\src\\main发v\\resources\\static\\appendix\\";


    //获取用户订阅的板块，未订阅的放在后面
    @RequestMapping(value = "/getPlate",method = RequestMethod.GET)
    public ResultData getUserPlate(Integer userId){
       List<SubPlate> userPlates = plateService.getUserPlate(userId);
        return ResultData.success("获取成功",userPlates.size(),userPlates);
    }

    //获取列表，获取全部或者用户订阅列表，按时间排序
    @RequestMapping(value = "/getNews", method = RequestMethod.GET)
    public ResultData getNewsList(@RequestParam(value = "userId", required = false) Integer userId) {
        List<NewsDetail> news;
        if (userId != null) {
            news = plateService.GetNewsByUser(userId);
        } else {
            news = plateService.GetAllNews();
        }

        return news.isEmpty() ? ResultData.error("该用户没有订阅") : ResultData.success("订阅列表", news.size(), news);
    }

    //进入详情页面
    @RequestMapping(value = "/detail/{id}",method = RequestMethod.GET)
    public ResultData getNewsDetail(@PathVariable("id") Integer newsId){
        NewsDetail newsDetail = plateService.GetNewsDetail(newsId);
        if (newsDetail != null)
            return ResultData.success("成功",1,newsDetail);
        return ResultData.error("无数据");
    }


    //搜索.用户或者标题或者内容
    @RequestMapping(value = "/searchKey",method = RequestMethod.GET)
    public ResultData SearchKey(String key, @RequestParam(value = "userId", required = false) Integer userId) {
        //默认key不为空
        List<NewsDetail> newsDetails = plateService.GetNewsBySearch(key, userId);
        if (newsDetails.isEmpty())
            return ResultData.error("搜结果为空");
        return ResultData.success("搜索成功",newsDetails.size(),newsDetails);
    }


    //消息发布模块
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public ResultData UserPublish(int userId,
                                  String title,
                                  String content,
                                  @RequestParam(required = false) String newsAppendix) {

        //            if (appendix.isEmpty()) {
//                //文件名
//                file = appendix.getOriginalFilename();
//                //文件名称
//                String name = file.substring(0, file.lastIndexOf("."));
//                //文件后缀格式
//                String suffix = file.substring(file.lastIndexOf("."));
//
//                filename = System.currentTimeMillis() + name + suffix;
//                //文件保存
//                appendix.transferTo(new File(FILE_PATH + filename));
        class data implements Serializable{
            private Integer publicId;

            public data(Integer publicId) {
                this.publicId = publicId;
            }

            public Integer getPublicId() {
                return publicId;
            }

            public void setPublicId(Integer publicId) {
                this.publicId = publicId;
            }
        }

        int i = plateService.PubContent(userId, title, content, newsAppendix);
        return i > 0 ? ResultData.success("发布成功", 1, new data(i)) :
                ResultData.error("发布失败");

    }


    //文件下载
    @RequestMapping("/download")
    public void DownloadFile(String fileName, HttpServletResponse response) {
        try {
            // path是指想要下载的文件的路径
            File file = new File(FILE_PATH+fileName);
//            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
//            log.info("文件后缀名：" + ext);

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();

        }
    }
}
